import os
import re
from filelist_parse.file_parse import file_parse
from port_parse.port_parse import portParse

class moduleports():
    def __init__(self):
        self.getfilesflag = 0


    def getmoduleports(self,module):
        if self.getfilesflag==0:
            raise Exception("please run getfiles first.")
        pp = portParse()
        for f in self.filelst:
            (fdir,fname)=os.path.split(f)
            fname_ext = fname.split(".")[-1]
            fname_pre = fname.split(".")[0]
            if fname_pre.lower() == module.lower() and fname_ext in ["v","sv"]:
                with open(f,"r") as fp:
                    pp.run(fp.read(),module)
                if pp.matched:
                    return (pp.getPortsInfo(),pp.getPortName())
        # If the search by name pattern does not find the corresponding module, the search will be extended to all files.
        if pp.matched==0:
            for f in self.filelst:
                with open(f,"r") as fp:
                    pp.run(fp.read(),module)
                if pp.matched:
                    return (pp.getPortsInfo(),pp.getPortName())

        return None

    def getfiles(self,incdir=["."],filelist=[]):
        self.getfilesflag = 1
        self.filelst = []
        (d,l,f)= self.setupparse()
        self.filelst.extend(f)
        for d in incdir+d:
            if os.path.exists(d) and os.path.isdir(d):
                files = os.listdir(d)
                for f in files:
                    if f.split(".")[-1] == "v" or f.split(".")[-1] == "sv":
                        self.filelst.append(os.path.abspath(d+"/"+f))
        for f in filelist+l:
            if os.path.exists(f):
                fp = file_parse()
                fp.run(f)
                self.filelst.extend(fp.getlist())

    def setupparse(self):
        state = 0
        incdir = []
        filelist = []
        files = []
        if os.path.exists("autoins.setup"):
            with open("autoins.setup","r") as f:
                for line in f:
                    if state==0:
                        if re.search("^\s*incdir\s*:\s*",line):
                            state = 1
                        elif re.search("^\s*filelist\s*:\s*",line):
                            state = 2
                        elif re.search("^\s*file\s*:\s*",line):
                            state = 3
                    elif state==1:
                        if re.search("^\s*filelist\s*:\s*",line):
                            state = 2
                        elif re.search("^\s*file\s*:\s*",line):
                            state = 3
                        else:
                            line = re.sub("\s","",line)
                            if os.path.exists(line):
                                incdir.append(line)
                    elif state==2:
                        if re.search("^\s*file\s*:\s*",line):
                            state = 3
                        else:
                            line = re.sub("\s","",line)
                            if os.path.exists(line):
                                filelist.append(line)
                    elif state == 3:
                        line = re.sub("\s","",line)
                        if os.path.exists(line):
                            files.append(line)
        return (incdir,filelist,files)



if __name__=="__main__":
    test = moduleports()
    test.getfiles(filelist=[])
    print(test.getmoduleports("a"))

